#include "mysqlDataBase.h"
#include <iostream>

/* 构造函数 */
MysqlDataBase::MysqlDataBase(const std::string &host, const std::string &user, const std::string &passwd)
{
    m_conn = mysql_init(NULL);

    m_host = host.c_str();
    m_user = user.c_str();
    m_passwd = passwd.c_str();
}

MysqlDataBase::~MysqlDataBase()
{
    if (m_conn != NULL)
    {
        close();
    }
}

/* 连接数据库 */
bool MysqlDataBase::connectDB(const std::string &connStr)
{

    if (mysql_real_connect(m_conn, m_host, m_user, m_passwd, connStr.c_str(), 3306, NULL, 0) == NULL)
    {
        std::cout << "mysql connect error." << std::endl;
        return false;
    }
    return true;
}

/* 执行Sql语句(exec) */
bool MysqlDataBase::executeSql(const std::string &sql)
{
    /* 查询数据 */
    if (mysql_query(m_conn, sql.c_str()))
    {
        std::cout << "file:" << __FILE__ << ", lines:" << __LINE__ << mysql_error(m_conn) << std::endl;
        return false;
    }
    return true;
}

/* 查询Sql语句(select) */
QueryResult MysqlDataBase::querySql(const std::string &sql)
{
    QueryResult result;

    /* 查询数据 */
    if (mysql_query(m_conn, sql.c_str()))
    {
        std::cout << "file:" << __FILE__ << ", lines:" << __LINE__ << mysql_error(m_conn) << std::endl;
        return result;
    }

    /* 从结果集里拿取数据 */
    MYSQL_RES *res = mysql_store_result(m_conn);
    if (res == NULL)
    {
        std::cout << "file:" << __FILE__ << ", lines:" << __LINE__ << mysql_error(m_conn) << std::endl;
        return result;
    }

    /* 获取几列数据 */
    unsigned int columns = mysql_num_fields(res);
    /* 获取几行数据 */
    unsigned int rows = mysql_num_rows(res);

    /* 获取字段名称  取列名 */
    MYSQL_FIELD *fields = mysql_fetch_field(res);
    /* 打印所有列名的信息 */
    for (int idx = 0; idx < columns; idx++)
    {
        result.columnName.push_back(fields[idx].name);
    }

    /* 获取每一行的数据 */
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(res)) != NULL)
    {
        std::vector<std::string> tmpRow;
        for (int idx = 0; idx < columns; idx++)
        {
            const char *tmp = NULL;
            if (row[idx] != NULL)
            {
                tmp = row[idx];
            }
            else
            {
                tmp = "NULL";
            }
            tmpRow.push_back(tmp);
        }
        result.rows.push_back(tmpRow);
    }
    /* 释放结果集 */
    mysql_free_result(res);
}

/* 关闭数据库连接 */
void MysqlDataBase::close()
{
    /* 关闭数据库 */
    mysql_close(m_conn);
    m_conn = NULL;
}


